package com.glodon.paas.account.security.spring.login;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

@Component("authenticationFailureHandler")
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException {
        String queryString = (String) request.getSession().getAttribute("loginUrlQueryString");
        if (StringUtils.isNotEmpty(queryString)) {
            if (StringUtils.contains(queryString, "error=true")) {
                response.sendRedirect(request.getContextPath() + "/login?" + queryString);
            } else {
                response.sendRedirect(request.getContextPath() + "/login?error=true&" + queryString);
            }

        } else {
            response.sendRedirect(request.getContextPath() + "/login?error=true");
        }
    }
}
